from rest_framework import generics
from home.models import AxfOrder,AxfCart,AxfOrdergoods
from order.order_serializers import OrderSerializer
from rest_framework.response import Response
from cart.MyAuthentications import CartAuthentication
from cart.MyPermissions import CartPermission
from order.order_status_constant import *
from order.OrderFilters import OrderFilter
from decimal import Decimal

# Create your views here.


class ListCreateOrderView(generics.ListCreateAPIView):
    '''
    get:
    获取订单数据
    post:
    创建订单
    '''
    queryset = AxfOrder.objects.all()
    serializer_class = OrderSerializer
    authentication_classes = (CartAuthentication,)
    permission_classes = (CartPermission,)
    filter_class = OrderFilter # 指定过滤器类。不能和filter_fields同时使用

    # 创建订单
    def create(self, request, *args, **kwargs): # 类似market/views.py中GoodsListView类中list()方法和user/views.py中UserLoginView类中create()方法的注释
        user=request.user # 通过认证后，认证类返回了user，可以从request中获取
        carts=AxfCart.objects.filter(c_user=user) # 当前用户的购物车
        goods_is_select=carts.filter(c_is_select=1) # 当前用户的购物车中已选择的商品

        order=AxfOrder() # 创建订单
        order.o_price=self.compute_total_price(goods_is_select)
        order.o_status=ORDER_STATUS_NOT_PAY # 订单状态常量在当前文件夹中order_status_constant.py中
        order.o_user=user
        order.save() # o_time字段设置了auto_now=True，创建或修改该模型对象时，自动将当前时间设为o_time字段的值(即自动更新该字段的值)

        self.add_to_ordergoods(goods_is_select,order)
        self.delete_from_cart(goods_is_select)

        return Response({
            'code':200,
            'msg':'请求成功',
            'data':{'order_id':order.id}
        })

    # 获取订单数据
    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset()) # filter_queryset()方法使用filter_class属性定义的过滤器对结果过滤。filter_queryset()方法中filter_backends是settings.py中REST_FRAMEWORK中DjangoFilterBackend
        queryset=queryset.filter(o_user=request.user) # 当前用户的所有订单
        serializer = self.get_serializer(queryset, many=True)
        return Response({
            'code':200,
            'msg':'请求成功',
            'data':serializer.data
        })

    def compute_total_price(self,goods_is_select): # 计算当前用户的购物车中已选择的商品的总价。复制的cart/views.py中ListCartView类中list()方法中第二种写法
        total_price=Decimal('0')
        for goods_in_cart in goods_is_select:
            total_price += Decimal(str(goods_in_cart.c_goods_num)) * Decimal(str(goods_in_cart.c_goods.price))
        return total_price

    def add_to_ordergoods(self,goods_is_ordered,order): # 将购物车中已创建订单的商品添加到订单商品表(AxfOrdergoods模型，axf_ordergoods表)
        # order_goods_list=[]
        for goods in goods_is_ordered:
            order_goods=AxfOrdergoods()
            order_goods.o_goods_num=goods.c_goods_num
            order_goods.o_goods=goods.c_goods
            order_goods.o_order=order
            order_goods.save()
            # order_goods_list.append(order_goods)
        # AxfOrdergoods.objects.bulk_create(order_goods_list) # 一次创建多个对象，比一次创建一个对象(创建一个对象save()一次)快，用的时候注释掉上面的save()并取消上面的两行注释

    def delete_from_cart(self,goods_is_ordered): # 将购物车中已创建订单的商品删除
        for goods in goods_is_ordered:
            goods.delete()